<template>
    <div class="government-container">
        <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
            <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
                <van-cell v-for="goverItem in golist" :key="goverItem.id" class="government-box">
                    <div class="flex beetween">
                        <nuxt-link :to="{ path: '/government/agency/' + goverItem.agencyid }" class="flex-item flex">
                            <div class="flex-item flex">
                                <div class="gover-icon">
                                    <van-image :src="goverItem.icon" width="100%" height="auto" fit="contain" />
                                </div>
                                <div class="gover-name">
                                    {{ goverItem.name }}
                                </div>
                            </div>
                        </nuxt-link>
                        <div class="right-btn">
                            +关注
                        </div>
                    </div>
                    <nuxt-link :to="{ path: '/government/' + goverItem.newsid, query: { cid: goverItem.agencyid } }">
                        <div class="gover-img flex">
                            <van-image :src="goverItem.breviaryimges" width="100%" height="auto" fit="contain" />
                        </div>
                        <div class="gover-title">
                            {{ goverItem.title }}
                        </div>
                    </nuxt-link>
                    <div class="gover-time">
                        {{ safeFormatRelativeTime(goverItem.addtime) }}
                    </div>
                </van-cell>
            </van-list>
        </van-pull-refresh>

    </div>
</template>

<script setup lang="ts">
// 政务页面逻辑 
const golist = ref<any[]>([]);
const loading = ref(false);
const finished = ref(false);
const refreshing = ref(false);
const currentPage = ref(1);
const pageSize = ref(10); 
const currentCategoryId = ref<number>(0);
//时间格式化
const dayjs = useDayjs();

const safeFormatRelativeTime = (time: string | null | undefined) => {
  if (!time) return '';
  const now = dayjs();
  const target = dayjs(time);
  
  // 如果是当天时间，显示相对时间（如 "2 小时前"）
  if (target.isSame(now, 'day')) {
    return target.fromNow();
  } 
  // 非当天时间，显示完整年月日（如 "2023-01-01"）
  return target.format('YYYY-MM-DD');
};

onMounted(async () => {
    // 获取政务数据
    const governmentData = await $fetch('/api/government/government');
    // 假设返回的数据结构为 { data: [...] }，取出 data 数组
    if (governmentData?.data && Array.isArray(governmentData.data)) {
        golist.value = governmentData.data;
        console.log(golist.value);
    } else {
        return
    }
});

// 刷新数据
const onRefresh = async () => {
    // 重置状态
    finished.value = false;
    currentPage.value = 1;

    // 重新获取第一页数据
    try {
        await fetchNewsList(1, false, currentCategoryId.value);
    } catch (error) {
        console.error('刷新新闻数据失败:', error);
    } finally {
        // 结束下拉刷新以及加载状态
        refreshing.value = false;
        loading.value = false;
    }
};


// 加载更多数据
const onLoad = async () => {
    if (finished.value) {
        loading.value = false;
        return;
    }

    try {
        // 加载下一页数据
        const nextPage = currentPage.value + 1;
        const loadedCount = await fetchNewsList(nextPage, true, currentCategoryId.value);
        if (loadedCount > 0) {
            currentPage.value = nextPage;
        }
    } catch (error) {
        console.error('加载更多新闻失败:', error);
    } finally {
        loading.value = false;
    }
};


// 获取新闻数据的函数
const fetchNewsList = async (pageindex: number = 1, append: boolean = false, cateid?: number) => {
    try {
        // 简化参数构建，直接传递cateid
        const queryParams: any = { pageindex, pagesize: pageSize.value };

        // 只要cateid存在，就添加到参数中
        if (cateid !== undefined) {
            queryParams.cateid = String(cateid);
        }

        console.log('fetchNewsList请求参数:', queryParams);

        const response = await $fetch('/api/government/government', {
            params: queryParams
        });

        if (response?.data && Array.isArray(response.data)) {
            // 有时后端会返回不同字段结构，这里尽量保持我们需要的字段
            const normalized = response.data.map((n: any) => ({
                id: String(n.id || n.newsid || n.articleid || ''),
                newsid: String(n.newsid || n.id || ''),
                title: String(n.title || n.subject || ''),
                summary: String(n.summary || n.description || n.intro || ''),
                breviaryimges: n.breviaryimges || n.picurl || n.thumb || '',
                releasetime: n.releasetime || n.posttime || '',
                author: n.author || n.source || '',
                cateid: n.cateid || n.classid || undefined,
                newstype: n.newstype || n.type || n.contenttype || ''
            }));

            if (append) {
                golist.value = [...golist.value, ...normalized];
                console.log('list.value:', golist.value);
            } else {
                golist.value = normalized;
            }
            // 如果返回的数据少于请求的数量，说明没有更多数据了
            finished.value = normalized.length < pageSize.value;
            return normalized.length;  
        }
    } catch (error) {
        console.error('获取新闻数据失败:', error);
    }
    return 0;
};
</script>

<style scoped>
:deep(.van-cell__value) {
    text-align: left !important;
}
.gover-name,
.right-btn{
    font-size: 12px;
    line-height: 22px;
    color: #000;
}
.gover-icon{
    width: 22px;
    height: 22px;
    margin-right: 6px;
    border-radius: 50%;
}

.gover-title{
    font-size: 16px;
    line-height: 23px;
    color: #000;
    margin: 8px 0;
}

.gover-img{
    margin-top: 10px;
}
.gover-time{
    color: #999;
    font-size: 10px;
    line-height: 14px;
}
</style>